from .view import Agent
from . import schema
from fastapi import APIRouter, Depends, Security
from package.connector.sql_db import db
from package.fastapi import permission


router_agent = APIRouter(prefix='/agent', tags=['采集代理'])
router_meta = {'module': '数据采集', 'sub_module': '采集代理'}


@router_agent.get('/', response_model=schema.PageAgent, openapi_extra=router_meta, name='agent_list_get',
                 summary='代理列表')
def agent_list_get(q: str = None,
             page: int = 1,
             page_size: int = 10,
             order_by: str = 'created_at desc',
             session=Depends(db.get_session),
             user=Security(permission.security, scopes=['agent:read'])):
    return Agent.get_page_items(session, q=q, page=page, page_size=page_size, order_by=order_by)


@router_agent.get('/{id}', response_model=schema.AgentItemOut, openapi_extra=router_meta, name='agent_get', 
                      summary='代理配置修改')
def agent_get(id: str,
                  session=Depends(db.get_session),
                  user=Security(permission.security, scopes=['agent:write'])):
    return Agent.get_item(session, filter_=[Agent.id == id])


@router_agent.patch('/{id}', response_model=schema.AgentOut, openapi_extra=router_meta, name='agent_patch', 
                      summary='代理配置修改')
def agent_patch(id: str,
                  body: schema.AgentEdit,
                  session=Depends(db.get_session),
                  user=Security(permission.security, scopes=['agent:write'])):
    return Agent.update_item(session, filter_=[Agent.id == id], update=body.dict())


@router_agent.delete('/', response_model=schema.AgentOut, openapi_extra=router_meta, name='agent_delete', 
                      summary='代理删除')
def agent_delete(body: schema.BatchId,
                  session=Depends(db.get_session),
                  user=Security(permission.security, scopes=['agent:write'])):
    return Agent.delete_items(session=session, filter_=[Agent.id.in_(body.ids)])
